import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/user',
      component: () => import('../layouts/UserLayout.vue'),
      meta: { requiresAuth: true, role: 'user' },
      children: [
        {
          path: '',
          name: 'UserLayout',
          redirect: '/user/chapters'
        },
        {
          path: 'chapters',
          name: 'ChapterList',
          component: () => import('../views/user/ChapterList.vue')
        },
        {
          path: 'question/:nodenum',
          name: 'QuestionPage',
          component: () => import('../views/user/QuestionPage.vue')
        }
      ]
    },
    {
      path: '/admin',
      component: () => import('../layouts/AdminLayout.vue'),
      meta: { requiresAuth: true, role: 'admin' },
      children: [
        {
          path: '',
          name: 'AdminLayout',
          redirect: '/admin/scripts'
        },
        {
          path: 'scripts',
          name: 'ScriptManagement',
          component: () => import('../views/admin/ScriptManagement.vue')
        },
        {
          path: 'users',
          name: 'UserManagement',
          component: () => import('../views/admin/UserManagement.vue')
        },
        {
          path: 'import',
          name: 'ImportExcel',
          component: () => import('../views/admin/ImportExcel.vue')
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth) {
    if (!userStore.token) {
      next('/login')
      return
    }
    
    // 如果有token但没有用户信息，尝试从数据库恢复
    if (!userStore.user) {
      const result = await userStore.restoreUser()
      if (!result.success) {
        next('/login')
        return
      }
    }
    
    if (to.meta.role === 'admin' && !userStore.user?.isadmin) {
      next('/user')
      return
    }
    
    if (to.meta.role === 'user' && userStore.user?.isadmin) {
      next('/admin')
      return
    }
  }
  
  next()
})

export default router
